import axios, { AxiosError } from "axios"
import { useUserStore } from "@/store/user"
import { router } from "@/router"
import { ElMenuItem, ElMessage } from "element-plus"
const instance = axios.create({
    baseURL: 'http://xue.cnkdl.cn:9082/mall-admin/',
    timeout: 5000
})


instance.interceptors.request.use(
    config => {
        let token = localStorage.getItem("token")
        if (token) {
            config.headers = {
                "Authorization": token
            }
        }
        return config
    }
)
instance.interceptors.response.use(res => {
    console.log(res.data.message);

    if (res.data.code == 401) {
        const userStore = useUserStore()
        // 删token
        localStorage.removeItem("token");
        // 删路由
        userStore.activeMenus.forEach(item => {
            router.removeRoute(item.name)
        })
        router.removeRoute("home")
        // 清空数据
        userStore.menus = []
        // 跳转到login
    }
    if (res.data.code !== 200) {
        ElMessage.error(res.data.message)
    }

    return res.data
},

    (err: AxiosError) => {
        // 约束的是这个Promise
        ElMessage.error(`请求出问题了，请联系管理员,错误信息为：${err.message}`)
        return Promise.reject((err))
    }
)
// intercets.interceptors.
export default instance



